package com.hxzy.projectssmplus.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.projectssmplus.dto.LoginDTO;
import com.hxzy.projectssmplus.dto.SysAdminUserDTO;
import com.hxzy.projectssmplus.entity.SysAdminUser;
import com.hxzy.projectssmplus.exception.ServiceException;
import com.hxzy.projectssmplus.mapper.SysAdminUserMapper;
import com.hxzy.projectssmplus.security.LoginUserDetails;
import com.hxzy.projectssmplus.security.TokenService;
import com.hxzy.projectssmplus.service.SysAdminUserService;
import com.hxzy.projectssmplus.util.BCryptUtils;
import com.hxzy.projectssmplus.util.GlobalConst;
import com.hxzy.projectssmplus.vo.AjaxResult;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Log4j2
@Service
public class SysAdminUserServiceImpl extends ServiceImpl<SysAdminUserMapper, SysAdminUser> implements SysAdminUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * spring security 认证管理类(管理用户信息，一会 conf/SeucrityConfig.java中去配置)
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService  tokenService;

  @Override
    public AjaxResult login(LoginDTO loginDTO) {

        //验证码是否正确
        String redisKey = GlobalConst.CAPTCHA_REDIS_PREF + loginDTO.getUuid();
        String redisValue = this.stringRedisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isBlank(redisValue)) {
            throw new ServiceException("验证码已过期，请重新输入!");
        }

        //比较验证码
        if (!redisValue.equalsIgnoreCase(loginDTO.getCode())) {
            throw new ServiceException("验证码错误!");
        }
        //移出验证码,防别人再使用
        this.stringRedisTemplate.delete(redisKey);

        // spring security 登录实现
        //创建一个用户名和密码类
        UsernamePasswordAuthenticationToken usernameAndPassword = new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword());

        // 会自动调用你写的UserDetailsServiceImpl中的loadUserByUsername
        Authentication authentication = null;
        try {
            authentication = this.authenticationManager.authenticate(usernameAndPassword);

        } catch (BadCredentialsException bad) {
            log.error("{0},用户的密码错误", loginDTO.getUsername());
            throw new ServiceException("用户名或密码错误");
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(e.getMessage());
        }
        //生成令牌 与入到 redis ，  使用jwt把uuid加一个密，返回
        LoginUserDetails loginUserDetails = (LoginUserDetails) authentication.getPrincipal();
        //创建令牌
        String token = this.tokenService.createToken(loginUserDetails);

        return AjaxResult.success_data(token);
    }



    private SysAdminUser searchByLoginName(String loginUserName){
        QueryWrapper<SysAdminUser> queryWrapper=new QueryWrapper<>();
       // System.out.println("losginusername         ");
        queryWrapper.eq("login_user_name", loginUserName);

        SysAdminUser adminUser = super.getOne(queryWrapper);
        return adminUser;
    }



    @Override
    public SysAdminUser findUserByUserName(String username) {
        return   this.searchByLoginName(username);
    }

    @Override
    public IPage<SysAdminUser> search(IPage iPage, SysAdminUserDTO sysAdminUserDTO) {
        QueryWrapper<SysAdminUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(sysAdminUserDTO.getLoginUserName())){
            queryWrapper.like("login_user_name",sysAdminUserDTO.getLoginUserName());
        }
        if (StringUtils.isNotBlank(sysAdminUserDTO.getPerms())){
            queryWrapper.like("perms",sysAdminUserDTO.getPerms());
        }
        if (StringUtils.isNotBlank(sysAdminUserDTO.getLocked())){
            queryWrapper.eq("locked",sysAdminUserDTO.getLocked());
        }
        IPage page = super.page(iPage, queryWrapper);
        return page;
    }

    @Autowired
    private SysAdminUserMapper sysAdminUserMapper;

    /**
     * 根据条件分页查询已分配用户角色列表
     * @param user 用户信息
     * @return
     */
    @Override
    public IPage<SysAdminUser> selectAllocatedList(IPage iPage, SysAdminUser user) {
        List<SysAdminUser> sysAdminUsers = this.sysAdminUserMapper.selectAllocatedList(iPage, user);
        iPage.setRecords(sysAdminUsers);
        return iPage;
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     * @param user 用户信息
     * @return
     */
    @Override
    public IPage<SysAdminUser> selectUnallocatedList(IPage iPage, SysAdminUser user) {
        List<SysAdminUser> sysAdminUsers = this.sysAdminUserMapper.selectUnallocatedList(iPage, user);
        iPage.setRecords(sysAdminUsers);
        return iPage;
    }
}
